from flask import json
from jinja2.tests import test_number
from openpyxl.styles.builtins import total
from peewee import JOIN, fn

from common.public import *
from orm.model import TestPaper, db, Test, TestDetails, QuestionBank
from view.baseview import BaseView


class TestPaperView(BaseView):
    def __init__(self):
        pass

    def checkTestTime(self, params):
        """
        检查考试次数
        """
        test = TestPaper.get(TestPaper.id == params["testId"])
        result = []
        where_condition = True       
        if test.series_id:
            where_condition = where_condition & (TestPaper.series_id == (test.series_id))        
        rows = TestPaper.select().where(where_condition)
        total = TestPaper.select().where(where_condition).count()
        testNumber = TestPaper.select(fn.MAX(TestPaper.test_number).alias('count')).where(where_condition)
        max = "0"
        for row in rows: 
            if int(row.test_number) > int(max):
                max = row.test_number
                # return super().resultSet(200, "ok", [])
            else:
                max = max
        if total >= 2:
            for row in rows:
                if int(test.test_number) == int(max):
                    return super().resultSet(200, "ok", [])
                else:
                    return super().resultSet(201, "ok", [])         
                    # return super().resultSet(201, "false", [])
        else: 
            return super().resultSet(200, "第一次考试", [])
        return super().resultSet(201, "ok", []) 

    @db.atomic()
    def updateQuestionBank(self, params):
        """
        更新试卷基本信息
        """
        where_condition = True
        test = TestPaper.get(TestPaper.id == params["testId"])
        if test.test_type != params["testType"]:
            TestDetails.delete().where(TestDetails.test_id == test.id).execute()
            rows = QuestionBank.select().where(where_condition).order_by(fn.Rand()).limit(int(params["questionTotal"]))
            for row in rows:
                 
                TestDetails.create(
                    test_id = test.id,
                    question_bank_id = row.id
                    )            
#             res = self.addPaperTest(params)
#             print(res['code'])
#             if res['code'] == 500:
#                 return super().resultSet(500, "新类型题库数量不够更新失败", [])
#             if res['code'] == 200:
#                 return super().resultSet(200, "更新成功", [])
        test.name = params["name"]
        test.test_type = params["testType"]
        test.pass_mark = params["passMark"]
        test.score = params["score"]
        test.total_score = params["totalScore"]
        test.test_number = params["testNumber"]
        test.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")    

    @db.atomic() 
    def removeQuestionBank(self, params):
        """
        删除试卷基本信息
        """
        where_condition = True
        testpaper = TestPaper.get(TestPaper.id == params["testId"])
        testpaper.delete_instance()
        print(params)
        TestDetails.delete().where(TestDetails.test_id == params["testId"]).execute()
        return super().resultSet(200, "删除成功", [])
        raise Exception("删除失败")    

    @db.atomic()   
    def save(self, params):
        """录入"""
        print(params["achievement"])
        test = TestPaper.get(TestPaper.id == params["id"])
        test.score = params["score"]
        test.save()
        where_condition = True
        if test.id:
            where_condition = where_condition & (TestDetails.test_id == test.id)
        rows = TestDetails.select().where(where_condition).order_by(TestDetails.id)
        total = TestDetails.select().where(where_condition).count()
        i = 0
        for row in rows: 
            print(row)
            print(params["achievement"][i]["id"])
            testdetail = TestDetails.get(TestDetails.id == params["achievement"][i]["id"])
            if params["achievement"][i]["isRight"] == True:
                right = "对"
            elif params["achievement"][i]["isRight"] == False:
                right = "错"
            elif params["achievement"][i]["isRight"] == None:
                right = "错"
            testdetail.is_right = right
            testdetail.answer_results = params["achievement"][i]["answerResults"]
            testdetail.save()
            i += 1
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
        
    def read(self, params):
        """读出"""
#         res = self.checkTestTime(params)
#         if res['code'] == 201: 
#             return super().resultSet(201, "不可生成试卷", [])
        result = []
        where_condition = True
        if params["testId"]:
            where_condition = where_condition & (TestPaper.id == (params["testId"]))
        rows = TestPaper.select().where(where_condition)
        total = TestPaper.select().where(where_condition).count()
        recs = []
        for row in rows:
            # .group_by(rec.question_bank.question_type)
            for rec in row.testdetails_set.join(QuestionBank, JOIN.RIGHT_OUTER, on = (QuestionBank.id == TestDetails.question_bank_id)).order_by(QuestionBank.question_type):
                # print(rec.question_bank.xuan_xiang)
                recs.append({"id":rec.id,
                             "answerResults":rec.answer_results,
                             "isRight":rec.is_right,
                             "testType":rec.question_bank.type,
                             "stestType":rec.question_bank.stype,
                            "questionType":rec.question_bank.question_type,
                            "rightchoose":rec.question_bank.rightchoose,
                            "tiMu":rec.question_bank.ti_mu,
                            "xuanXiang":json.loads(rec.question_bank.xuan_xiang),
                            "timuAddTime":rec.question_bank.add_time,
                            "timuUpdateTime":rec.question_bank.update_time,
                             })
            if recs.__len__() == 0:
                recs.append({"id":"",
                             "answerResults":"",
                             "isRight":""})
            if row.add_time != None:
                row.add_time = time.strftime("%Y-%m-%d", time.strptime(str(row.add_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            testTotalTimes = 0
            if row.exam_id != 0:
                row2 = Test.select().where(Test.id == row.exam_id).first() 
                testTotalTimes = row2.test_total_times       
            data = {
                "id":row.id,
                "seriesId":row.series_id,
                "examId":row.exam_id,
                "score":row.score,
                "testNumber":row.test_number,
                "name":row.name,
                "identityCard":row.identity_card,
                "passMark":row.pass_mark,
                "questionTotal":row.question_total,
                "testType":row.test_type,
#                 "stestType":row.stestType
                "totalScore":row.total_score,
                "testTotalTimes":testTotalTimes,
                "add_time":row.add_time,
                "update_time":row.update_time,
                "recs":recs
             }
            result.append(data)
        return super().resultSet(200, "", result, total = total)

    def brush(self, params):
        """读出"""
        print(params)
        result = []
        where_condition = True
        if (params["type"] != "") & (params["type"] != "全部"):
            where_condition = where_condition & (QuestionBank.type == params["type"])
#         if params["stestType"]:
#             where_condition = where_condition & (QuestionBank.stype == params["stestType"])
        where_condition1 = where_condition & (QuestionBank.question_type == TEST_DANXUAN)
        where_condition2 = where_condition & (QuestionBank.question_type == TEST_DUOXUAN)
        danxuan_query = QuestionBank.select().where(where_condition1)
        duoxuan_query = QuestionBank.select().where(where_condition2)
        query1 = danxuan_query.order_by(fn.Rand()).limit(10)
        query2 = duoxuan_query.order_by(fn.Rand()).limit(10)
        danxuantotal = query1.count()
        duoxuantotal = query2.count()
        if danxuantotal < 10:
            query2 = duoxuan_query.order_by(fn.Rand()).limit(20 - danxuantotal)
        if duoxuantotal < 10:
            query1 = danxuan_query.order_by(fn.Rand()).limit(20 - duoxuantotal)
        rows = (query1 + query2).order_by(fn.Rand())
        for row in rows:
            data = ({"id":row.id,
                         "testType":row.type,
                         "stestType":row.stype,
                        "questionType":row.question_type,
                        "rightchoose":row.rightchoose,
                        "tiMu":row.ti_mu,
                        "xuanXiang":json.loads(row.xuan_xiang),
                        "timuAddTime":row.add_time,
                        "timuUpdateTime":row.update_time,
                         })
            result.append(data)
        return super().resultSet(200, "", result)
    def queryPhoneTest(self, params):
        """根据条件取得我的s列表，params：条件参数"""
        print(params)
        result = []
        # 考试还没考的
        rows = TestPaper.select().join(Test, JOIN.RIGHT_OUTER, on=(Test.id == TestPaper.exam_id))\
            .where((TestPaper.name==params["name"])& (TestPaper.score=="")& (Test.state=="进行中"))
        arr = [{"state":"", "exam_name":""}]
        print(rows)
        for row in rows:
            if row.exam_id == 0:
                arr[0]["state"] = "进行中"
                arr[0]["exam_name"] = "应聘考试"
            elif row.exam_id != 0:
                r = Test.select().where(Test.id == row.exam_id)
                arr[0]["state"] = r[0].state
                arr[0]["exam_name"] = r[0].name        
            data = {
                "id":row.id,
                "name":row.name,
                "score":row.score,
                "state":arr[0]["state"],
                "exam_name":arr[0]["exam_name"]
             }
            result.append(data)
#         # 考试次数没满的
#         rows = TestPaper.select().join(Test, JOIN.RIGHT_OUTER, on=(Test.id == TestPaper.exam_id))\
#             .where((TestPaper.name==params["name"])& (TestPaper.score!="")& (Test.state=="进行中"))\
#             .group_by(TestPaper.exam_id)\
#             .having(fn.MAX(TestPaper.test_number) < Test.test_total_times)
#         for row in rows:
#             if row.exam_id == 0:
#                 arr[0]["state"] = "进行中"
#                 arr[0]["exam_name"] = "应聘考试"
#             elif row.exam_id != 0:
#                 r = Test.select().where(Test.id == row.exam_id)
#                 arr[0]["state"] = r[0].state
#                 arr[0]["exam_name"] = r[0].name        
#             data = {
#                 "id":row.id,
#                 "name":row.name,
#                 "score":row.score,
#                 "state":arr[0]["state"],
#                 "exam_name":arr[0]["exam_name"]
#              }
#             result.append(data)
        
        return super().resultSet(200, "", result)
    def queryTest(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        print(params)
        result = []
        where_condition = True
        where_condition_user = False
        if params["type"]:
            where_condition = where_condition & (TestPaper.test_type == params["type"])
        if params["addTime"]:
            where_condition = where_condition & ((TestPaper.add_time >= params["addTime"][0] + " 00:00:00") \
                                               & (TestPaper.add_time <= params["addTime"][1] + " 23:59:59"))
        if params["updateTime"]:
            where_condition = where_condition & ((TestPaper.update_time >= params["updateTime"][0] + " 00:00:00") \
                                               & (TestPaper.update_time <= params["updateTime"][1] + " 23:59:59"))
       
        if params["names"]:
            where_condition = where_condition & (TestPaper.name.in_(params["names"]))
        if params["name"]:
            likestr = "%" + params["name"] + "%"       
            where_condition = (TestPaper.name ** likestr)
            where_condition = where_condition & (TestPaper.exam_id == 0)
        if params["testName"]:
            likestr = "%" + params["testName"] + "%"       
            where_condition = (Test.name ** likestr)            
#             where_condition = where_condition & (Test.name == params["testName"])
        rows = TestPaper.select(TestPaper, Test.name.alias('testname')).join(Test, JOIN.LEFT_OUTER, on = (Test.id == TestPaper.exam_id)).where(where_condition)
        rows = rows.order_by(TestPaper.add_time.desc(), TestPaper.name.desc(), TestPaper.test_number.asc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        total = rows.count()
        for row in rows:
            arr = [{"state":""}]
            if row.exam_id == 0:
                arr[0]["state"] = "进行中"
                testname = ""
            elif row.exam_id != 0:
                r = Test.select().where(Test.id == row.exam_id)
                arr[0]["state"] = r[0].state  
                testname = row.test.testname            
            recs = []
            for rec in row.testdetails_set:
                answer_results = rec.answer_results
                if rec.answer_results:
                    if rec.question_bank.question_type == "单选":
                        answer_results = rec.answer_results
                    elif rec.question_bank.question_type == "多选":
                        print(rec.answer_results)
                        answer_results = rec.answer_results
                recs.append({"id":rec.id,
                             "answer_results":answer_results,
                             "is_right":rec.is_right,
                             "type":rec.question_bank.type,
                            "question_type":rec.question_bank.question_type,
                            "rightchoose":eval(rec.question_bank.rightchoose),  # split(',')
                            "ti_mu":rec.question_bank.ti_mu,
                            "xuan_xiang":json.loads(rec.question_bank.xuan_xiang),
                            "timu_add_time":rec.question_bank.add_time,
                            "timu_update_time":rec.question_bank.update_time,
                             })
            if recs.__len__() == 0:
                recs.append({"id":"",
                             "answer_results":"",
                             "is_right":"",
                              "type":"",
                              "question_type":"",
                              "rightchoose":"",
                              "ti_mu":"",
                              "xuan_xiang":"",
                              "timu_add_time":"",
                              "timu_update_time":"",
                              })
            if row.add_time != None:
                row.add_time = time.strftime("%Y-%m-%d", time.strptime(str(row.add_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
        
            data = {
                "id":row.id,
                "score":row.score,
                "testNumber":row.test_number,
                "name":row.name,
                "identityCard":row.identity_card,
                "passMark":row.pass_mark,
                "testType":row.test_type,
                "testname":testname,
                "totalScore":row.total_score,
                "questionTotal":row.question_total,
                "add_time":row.add_time,
                "update_time":row.update_time,
                "recs":recs,
                "state":arr[0]["state"]
             }
            result.append(data)
        return super().resultSet(200, "", result, total = total)

    @db.atomic() 
    def addPaperTest(self, params):
        print(params)
        """
        新增随机生成试卷
        """ 
        result = []
        where_condition = True
        if params["testType"]:
            where_condition = where_condition & (QuestionBank.type == params["testType"])
#         if params["stestType"]:
#             where_condition = where_condition & (QuestionBank.stype == params["stestType"])
        if params["danxuan"]:
            where_condition1 = where_condition & (QuestionBank.question_type == TEST_DANXUAN)
        if params["duoxuan"]:
            where_condition2 = where_condition & (QuestionBank.question_type == TEST_DUOXUAN)
        total_danxuan = QuestionBank.select().where(where_condition1).count()
        total_duoxuan = QuestionBank.select().where(where_condition2).count()
        print(total_danxuan)
        print(total_duoxuan)
        if int(params["danxuan"]) > total_danxuan:
            return super().resultSet(500, "题库不够添加失败", result)
        if int(params["duoxuan"]) > total_duoxuan:
            return super().resultSet(500, "题库不够添加失败", result)
        test = TestPaper.create(
            identity_card = params["identityCard"],
            name = params["name"],
            test_number = params["testNumber"],
            pass_mark = params["passMark"],
            test_type = params["testType"],
#             exam_id = params["examId"],
#             stest_type = params["stestType"],
            question_total = params["questionTotal"],
            total_score = params["totalScore"],
            add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        )
        if params["examId"]:
            test.exam_id = params["examId"]
        else:
            test.exam_id = 0
        test.save()
        result.append(test.id)
        if int(test.test_number) == 1:
            test.series_id = test.id
            
        else:
            test.series_id = params["seriesId"]
        test.save()
        if params["danxuan"]:
            where_condition1 = where_condition & (QuestionBank.question_type == "单选")
        if params["duoxuan"]:
            where_condition2 = where_condition & (QuestionBank.question_type == "多选")
        query1 = (QuestionBank.select().where(where_condition1).order_by(fn.Rand()).limit(int(params["danxuan"])))
        query2 = (QuestionBank.select().where(where_condition2).order_by(fn.Rand()).limit(int(params["duoxuan"])))
        rows = (query1 + query2).order_by(fn.Rand())
        # rows = QuestionBank.select().where(where_condition).order_by(fn.Rand()).limit(int(params["danxuan"]))
        for row in rows:
             
            TestDetails.create(
                test_id = test.id,
                question_bank_id = row.id
                )
        return super().resultSet(200, "添加成功", result)
        raise Exception("添加失败")
